package cn.coder.easyjson.spring;

import java.io.IOException;
import java.nio.charset.Charset;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import cn.coder.easyjson.JSON;

public class EasyJsonHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
	private static final Logger log = LoggerFactory.getLogger(EasyJsonHttpMessageConverter.class);
	private static final Charset CHARSET = Charset.forName("UTF-8");

	public EasyJsonHttpMessageConverter() {
		super(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN);
	}

	@Override
	protected boolean supports(Class<?> clazz) {
		return true;
	}

	@Override
	protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotReadableException {
		String data = StreamUtils.copyToString(inputMessage.getBody(), CHARSET);
		if (JSON.validObject(data))
			return JSON.parse(data, clazz);
		if (JSON.validArray(data))
			return JSON.parseArray(data, clazz);
		return data;
	}

	@Override
	protected void writeInternal(Object t, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		if (t != null) {
			String result = JSON.toJSON(t);
			if (log.isDebugEnabled())
				log.debug("json:{}", result);
			outputMessage.getBody().write(result.getBytes(CHARSET));
		}
	}
}
